﻿<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

<script type="text/javascript">

    /* Config params */
    var use_map = 1;
    var use_location = 1;
    var update_timeout = 2;

    /* Internal vars */
    var playersArray = [];
    var applesArray = [];
    var map = '';
    var lat_center = 32.0689212;
    var lng_center = 34.7829502;
    var errors = 0;
    var init_done = 0;
    var game_update;
    var pos_update_timer = 0;
    var my_id = 3557;
    
    /* Game state:
       0 - Unknown
       1 - Initialized
       2 - Running
       3 - Finished */
    var game_state = 0;

    /* For testing only */
    var lat_fake = 40.714;
    var lng_fake = -74.005;
    var lat_dir_fake = -1 + 2 * Math.floor(Math.random()*2);
    var lng_dir_fake = -1 + 2 * Math.floor(Math.random()*2);

    function dbg_print(str) {
        $('#dbg').prepend('<p>' + str + '</p>');
        console.log(str);
    }

    function user_print(str) {
        $('#info').html('<h2>'+ str + '</h2>');
        dbg_print('USER: ' + str);
    }

    if (use_map) {
    var pacman_image = new google.maps.MarkerImage('http://tlvivi.co.il/pacman.gif',
      new google.maps.Size(14, 14),
      new google.maps.Point(0,0),
      new google.maps.Point(7, 7));

    var ghost_image = new google.maps.MarkerImage('http://tlvivi.co.il/ghost.gif',
      new google.maps.Size(14, 14),
      new google.maps.Point(0,0),
      new google.maps.Point(7, 7));

    var apple_image = new google.maps.MarkerImage('http://tlvivi.co.il/apple.png',
      new google.maps.Size(10, 10),
      new google.maps.Point(0,0),
      new google.maps.Point(5, 5));
    }

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

    var Apple = function apple(lat, lng, id) {
        this.lat = lat;
        this.lng = lng;
        this.id = id;

        dbg_print('New apple ' + lat + ':' + lng);

        if (use_map) {
            var latlng = new google.maps.LatLng(this.lat, this.lng);

            this.marker = new google.maps.Marker({
                position: latlng,
                title: 'Apple',
                icon: apple_image,
                map: map
            });
        }

        this.remove = function() {
            dbg_print('Remove apple #' + this.id);
            if (use_map)
                this.marker.setMap();
        };
        
        applesArray.push(this);
    }

    var Player = function player(lat, lng, type, name, id) {
        this.lat = lat;
        this.lng = lng;
        this.type = type;
        this.name = name;
        this.id = id;
        
        dbg_print(name + ' (' + id + ')  ' + lat + ':' + lng);

        if (use_map) {
        var latlng = new google.maps.LatLng(this.lat, this.lng);

        this.marker = new google.maps.Marker({
            position: latlng,
            title: this.Name,
            icon: type == 1 ? pacman_image : ghost_image,
            map: map
        });
        }

        this.remove = function() {
            dbg_print('Remove player ' + this.id);
            if (use_map)
                this.marker.setMap();
        };
        
        playersArray.push(this);
    }    

    function fake_coordiates(callback) {
        lat_fake = lat_fake + 0.0001 * lat_dir_fake;
        lng_fake = lng_fake + 0.0001 * lng_dir_fake;

        if (lat_fake > (lat_center + 0.003) || lat_fake < (lat_center - 0.003))
            lat_dir_fake *= -1;

        if (lng_fake > (lng_center + 0.003) || lng_fake < (lng_center - 0.003))
            lng_dir_fake *= -1;

        callback(lat_fake, lng_fake);
    }

    function scrollMap(lat, lng) {
            if (game_state < 1)
                return;

            if (playersArray.length <= 0)
                return;
    
            var myLatlng = new google.maps.LatLng(lat, lng);

            for (i in playersArray)
              if (playersArray[i].id == 1) {
                    user_print('UP ' + lat + ' : ' + lng);
                    playersArray[1].marker.setPosition(myLatlng);
              }
    }
    var curr = 0;
    function scrollMap_cb(position) {
        curr = curr+1;
        user_print('Got location update... ' + curr);
        scrollMap(position.coords.latitude, position.coords.longitude);
    }

    function fake_scrollMap() {
        fake_coordiates(scrollMap);
        setTimeout(fake_scrollMap, 1000);
    }

    function get_location(callback) {
        if (!use_location)
        {
            fake_coordiates(callback);
            setTimeout(fake_scrollMap, 10000);
            return;
        }

        if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                        dbg_print('Calling callback');
                       callback(position.coords.latitude, position.coords.longitude);
                    }, function(position_error) {
                        /* Error getting location */
                        errors += 1;
                        user_print('Error getting location (' + position_error.message + ')');
                        setTimeout(game_update, 1000 * update_timeout);
                    }, {
                    enableHighAccuracy: true
                 });
       /*
            if (!pos_update_timer) {
                pos_update_timer = navigator.geolocation.watchPosition(scrollMap_cb);
                dbg_print('Starting auto update [' + pos_update_timer + ']');
            }
*/
        } else {
            user_print('The W3C Geolocation API isn\'t supported');
        }
        
        dbg_print('Finished get_location');    
    }

    function update_state(data) {
        dbg_print('Got state update !');

        /* Display all players */
        if (data.Players) 
        {
            dbg_print('Remove old players');

            /* Remove previous map entities */
            while (playersArray.length) {
                player = playersArray.pop();
                player.remove()
            }

            dbg_print('Load up new players ' + data.Players.length);

            $.each(data.Players, function(i,item) { 
                    var player = new Player(item.Lat, item.Lng, item.Role, item.Name, item.EntityId)
            });
        }
        
        
        $.each(data.RemovedAppleIds, function(i,item) { 
            for (i in applesArray)
              if (applesArray[i].id == item) {
                    applesArray[i].remove();
                    applesArray.splice(i, 1);
              }
        });

        if (data.Message)
            user_print(data.Message);

        dbg_print('Starting timer...');
        setTimeout(game_update, 1000 * update_timeout);
    }
   
    function update_position(lat, lng) {
        if (errors > 5) {
            dbg_print('Too many errors...');
            return;
        }

        dbg_print('Got updated position ' + lat + ':' + lng);

        $.ajax({
            url: "http://tlvivi.co.il/PollServer.ashx?jsoncallback=?", 
            dataType: "jsonp",
            data: { 'EntityId':my_id, 'geolat':lat, 'geolng':lng, 'IsEnabled':true, 'UpdateMeForTheLastXSeconds':'5' },
            jsonpString: "jsoncallback",
            success: update_state,
            });

    }

    function game_update() {
        if (errors > 5) {
            dbg_print('Too many errors...');
            return;
        }

        dbg_print('Starting update sequence');
        get_location(update_position);
    };

    function init_map() {
        var latlng = new google.maps.LatLng(lat_center, lng_center);
    
        var myOptions = {
          zoom: 16,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.SATELLITE /* ROADMAP - No road map for Israel due to legal matters :-( */
        };

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }

    function init_game(data)
    {
        if (game_state == 0)
            game_state = 1;
        else 
            return;
            
        if (data == null)
        {
            dbg_print('Game init passed no data');
            return;
        }

        dbg_print('Got initial json data, start init.. ');

        if (use_map)
            init_map();

        /* Load up game borders */    
        if (data.GameBorderPoints) 
        {
            var poly = [];

            $.each(data.GameBorderPoints, function(i,item) { 
                poly.push(new google.maps.LatLng(item.Lat, item.Lon));
            });
            poly.push(new google.maps.LatLng(data.GameBorderPoints[0].Lat, data.GameBorderPoints[0].Lon));

            dbg_print('Add game borders: ' + poly);
            var polyline = new google.maps.Polyline({
                path: poly,
                strokeColor: "#FF0000",
                strokeOpacity: 0.5,
                strokeWeight: 2
              });
            polyline.setMap(map);
    
        }

        /* Load up apples data */
        if (data.Apples) 
        {
            $.each(data.Apples, function(i,item) { 
                    var apple = new Apple(item.Lat, item.Lng, item.EntityId)
            });
        }


        
        /* Start the update sequence */
        game_update();
    }

    function init_position(lat, lng) {

        lat_center = lat
        lng_center = lng
        my_id = getUrlVars()["me"];

        /* Got location */
        user_print('You are #' + my_id + ' at: ' + lat + ' : ' + lng);

        $.ajax({
            url: "http://tlvivi.co.il/gameState.ashx?jsoncallback=?", 
            dataType: "jsonp",
            data: { 'EntityId': my_id },
            jsonpString: "jsoncallback",
            success: init_game,
            });

    }
    
    function reinit_position() {
        init_position(lat_center, lng_center);
    }

    function initialize() {
        $("#info").ajaxError(function(event, request, settings){
            errors += 1;
            
            user_print("Error requesting page " + settings.url);
            
            if (errors > 5) {
                user_print('Too many errors, stopping.');
                return;
            }
            
            switch (game_state) {
            case 0:
                setTimeout(reinit_position, 200);
                break;
            case 1:
                setTimeout(game_update, 1000 * update_timeout); 
                break;
            default:
                dbg_print('Ajax error at unknown state: ' + game_state);
            }
        });

        get_location(init_position);
    }

    $(document).ready(function() {
        dbg_print('MAIN: Start page init..');
        initialize();
    });

</script>

    </head>

    <body>
        <div id="info"></div>

        <div id="map_canvas" style="height:300px; width:400px;"></div>
        <div id="dbg"></div>
    </body>
</html>



































